import React, { useState, useEffect } from 'react';
import { Input, Modal, Form, message, Select, Checkbox, Tooltip, Icon } from 'antd';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { addProbeStrategy, updateProbeStrategy } from '@api/task';
import { PORT_RE, PORT_RANGE_RE, NAME_RE } from '@util/constants';
import validatorCreator from '@util/validator-creator';
// import getPortsCount from '@util/get-ports-count';
import CheckboxGroup from 'antd/lib/checkbox/Group';
import { getAllPortTemplates } from '@api/task';
import CutArray from '@util/cut-array';
import './index.less';

const FormItem = Form.Item;
const TextArea = Input.TextArea;
const prefixCls = 'port-strategy-modal';

const formItemLayout = {
  labelCol: {
    span: 6
  },
  wrapperCol: {
    span: 18
  }
};

const ignoreNetworkPrinterPortLayout = {
  labelCol: {
    span: 7
  },
  wrapperCol: {
    span: 12
  }
};

const PortManageModal = props => {
  const {
    modalVisible,
    changeModalVisible,
    form: { getFieldDecorator, setFieldsValue, getFieldValue, resetFields },
    getPortList,
    detail
  } = props;
  const [ports, setPorts] = useState([]);
  const [portTemplates, setPortTemplates] = useState([]);
  const [portTemplateLoading, setPortTemplateLoading] = useState(false);
  const [portTemplatesMap, setPortTemplatesMap] = useState({});
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [portErro, setPortErro] = useState();
  const [cachePortd, setcachePortd] = useState();
  const [cacheCustom, setCacheCustom] = useState();
  const onClickSubmit = () => {
    const {
      form: { validateFieldsAndScroll }
    } = props;
    validateFieldsAndScroll((err, values) => {
      if (err || portErro) {
        return;
      }
      let probePortId = values.detectionPortId;
      // let rowPort = portTemplates.find(r => r._id === probePortId);
      let detectionPortList;
      if (!ports) {
        message.error('端口不能为空！');
        return;
      }
      if (ports.length > 0) {
        detectionPortList = _.uniq(_.split(ports, ','));
      } else {
        detectionPortList = [];
      }
      if (detectionPortList.length === 0) {
        message.error('端口不能为空！');
        return;
      }
      const formatedData = {
        name: values.name.replace(/\s/g, ''),
        detectionPortList: detectionPortList,
        isPortCustom: false,
        fingerprintDetection: values.fingerprintDetection,
        depthDetect: values.depthDetect,
        protocolType: values.protocolType,
        portDetectionOnly: values.portDetectionOnly || false,
        ignorePrinterPortCheck: values.ignorePrinterPortCheck || false
      };

      if (probePortId !== '01') {
        formatedData.detectionPortId = probePortId;
      }
      let todo, successInfo, body;
      if (_.get(detail, '_id', '')) {
        todo = updateProbeStrategy;
        successInfo = '修改成功';

        body = { id: _.get(detail, '_id', '') };
      } else {
        todo = addProbeStrategy;
        successInfo = '添加成功';
        body = {};
      }
      setConfirmLoading(true);

      todo({ ...body, ...formatedData })
        .then(() => {
          message.success(successInfo);
          setConfirmLoading(false);
          getPortList();
          changeModalVisible(false);
        })
        .catch(e => {
          message.error(e.message);
          setConfirmLoading(false);
        });
    });
  };

  const loadPortTemplates = () => {
    setPortTemplateLoading(true);
    getAllPortTemplates().then(res => {
      const portTemplates = _.get(res, 'data.data.list', []);
      const portTemplatesMap = portTemplates.reduce((total, current = {}, index) => {
        total[current._id] = index;
        return total;
      }, {});
      portTemplates.push({
        is_build_in: false,
        name: '自定义',
        _id: '01'
      });
      setPortTemplates(portTemplates);
      setPortTemplatesMap(portTemplatesMap);
      setPortTemplateLoading(false);
    });
  };

  const portsValidate = value => {
    let flag = '';
    if (!value) {
      flag = '端口不能为空';
    }
    let ports = value.split(',');
    ports.map(item => {
      if (!PORT_RE.test(item) && !PORT_RANGE_RE.test(item)) {
        flag = '请输入正确格式的端口';
      }
    });
    // if (getPortsCount(ports) > MAX_DETECTION_PORT) {
    //   callback(`端口数不能超过${MAX_DETECTION_PORT}`);
    // }
    return flag;
  };

  const onPortTemplateChange = value => {
    const ports = _.get(portTemplates, `${portTemplatesMap[value]}.ports`, []);
    setPorts(ports);
    setFieldsValue({ ignorePrinterPortCheck: false });
  };

  const onChangeTextArea = value => {
    // 如果是自定义
    if (getFieldValue('detectionPortId') === '01') {
      let erro = portsValidate(value.target.value);
      setPortErro(erro);
    } else {
      setPortErro();
    }
    setPorts(value.target.value);
  };

  const textAreaBlur = () => {
    if (getFieldValue('ignorePrinterPortCheck')) {
      // eslint-disable-next-line no-use-before-define
      changePorts(null, true);
    }
  };

  const changeFingerprintDetection = value => {
    if (value.target.checked) {
      let protocolType = getFieldValue('protocolType');
      !protocolType.includes('TCP') ? protocolType.push('TCP') : null;
      setFieldsValue({
        protocolType: protocolType
      });
    }
  };

  const changePorts = (e, checked) => {
    if (ports && !portTemplateLoading && (_.get(e, 'target.checked') || checked)) {
      setcachePortd();
      setCacheCustom(ports);
      let newPorts = Array.isArray(ports) ? ports : ports.split(',');
      // eslint-disable-next-line eqeqeq
      newPorts = newPorts.filter(r => r != 9100);
      let newArray = [];
      for (let i = 0; i < newPorts.length; i++) {
        if (newPorts[i].split('').includes('-')) {
          // 排除值为 3 的项
          newArray.push(CutArray(newPorts[i]));
        } else {
          newArray.push(newPorts[i]);
        }
      }
      // 如果当前过滤了打印机后端口为空就返回为自定义模版
      if (newArray.length === 0) {
        setFieldsValue({ detectionPortId: '01' });
      }
      setPorts(newArray);
    } else {
      if (!_.get(e, 'target.checked')) {
        // 非自定义时如果选中了模版 取消忽略的时候返回原来的值
        if (getFieldValue('detectionPortId') !== '01') {
          setcachePortd(getFieldValue('detectionPortId'));
          loadPortTemplates();
        }
        //  如果是自定义
        else {
          //  如果是自定义详情并且是第一次点击取消则忽略逻辑
          if (_.get(detail, '_id', '') && _.get(detail, 'first')) {
            detail.first = false;
          } else {
            setPorts(cacheCustom);
            setCacheCustom();
          }
        }
      }
    }
  };

  useEffect(() => {
    if (portTemplates) {
      let id = '';
      if (portTemplates && !detail) {
        setPorts();
        // 新增默认端口是top1000;
        if (modalVisible && !cachePortd) {
          const top1000 = portTemplates.filter(item => item.name === 'Top1000');
          if (top1000[0]) {
            id = top1000[0]._id;
            setPorts(top1000[0].ports);
          }
        }
      }
      if (cachePortd) {
        const item = portTemplates.filter(item => item._id === cachePortd);
        if (item[0]) {
          id = item[0]._id;
          setPorts(item[0].ports);
        }
      }
      if (id) {
        setFieldsValue({ detectionPortId: id });
      }
    }
  }, [portTemplates]);

  useEffect(() => {
    if (modalVisible === true) {
      loadPortTemplates();
    }
    resetFields();
    if (modalVisible && detail) {
      if (_.get(detail, 'detectionPortOid._id')) {
        detail.detectionPortId = _.get(detail, 'detectionPortOid._id');
      }
      if (!detail.detectionPortId) {
        detail.detectionPortId = '01';
      }
      setFieldsValue({ ...detail });
      if (detail.detectionPortList) {
        setPorts(detail.detectionPortList);
      }
    }
    if (modalVisible && !detail) {
      setFieldsValue({
        protocolType: ['ICMP', 'UDP', 'TCP'],
        fingerprintDetection: true,
        depthDetect: true
      });
    }
    // 关闭弹窗新增缓存
    if (!modalVisible) {
      setcachePortd();
    }
  }, [modalVisible]);

  useEffect(() => {
    if (_.get(detail, '_id') && _.get(detail, 'ignorePrinterPortCheck')) {
      detail.first = true;
    }
  }, [detail]);
  return (
    <div className="password-modal">
      <Modal
        maskClosable={false}
        title={
          <span style={{ fontWeight: 600 }}>
            {_.get(detail, '_id', '') ? '修改' : '添加'}探测策略模版
          </span>
        }
        className={`${prefixCls}-modal`}
        visible={modalVisible}
        width={520}
        portManage
        onCancel={() => changeModalVisible(false)}
        onOk={onClickSubmit}
        confirmLoading={confirmLoading}
        okButtonProps={{ className: 'button-forwards' }}
      >
        <Form labelAlign="left">
          <FormItem {...formItemLayout} key="name" label="名称" colon={false}>
            {getFieldDecorator('name', {
              rules: [
                {
                  validator: validatorCreator('名称', {
                    required: true
                  }),
                  required: true
                },
                {
                  pattern: NAME_RE,
                  message: '您输入的格式有误，仅支持中文、英文、数字、特殊字符 - 、— \\ _ / ：~'
                },
                {
                  max: 32,
                  message: '您输入的内容超过32个字符限制'
                }
              ]
            })(<Input placeholder="请输入中文、英文、特殊字符或数字，不超过32个字符" />)}
          </FormItem>
          <FormItem {...formItemLayout} key="detectionPortId" label="探测端口" colon={false}>
            {getFieldDecorator('detectionPortId', {
              rules: [
                {
                  validator: validatorCreator('探测端口', {
                    required: true
                  })
                }
              ]
            })(
              <Select
                optionLabelProp="title"
                dropdownClassName="tm-asset-modal-select-drawdown"
                onChange={onPortTemplateChange}
                loading={portTemplateLoading}
                style={{ width: 210 }}
              >
                {portTemplates.map(portTemplate => (
                  <Select.Option
                    title={portTemplate.name}
                    value={portTemplate._id}
                    key={portTemplate._id}
                  >
                    <div className="template-item">{portTemplate.name}</div>
                  </Select.Option>
                ))}
              </Select>
            )}
            <TextArea
              placeholder="请使用“-”指定端口范围，使用“，”分割端口。&#10;例如：21，22，23，10-50"
              className="ports"
              rows={3}
              onChange={onChangeTextArea}
              value={ports}
              onBlur={textAreaBlur}
              disabled={getFieldValue('detectionPortId') !== '01'}
            />
            <span style={{ color: 'red' }}>{portErro}</span>
          </FormItem>
          <FormItem
            key="port"
            {...ignoreNetworkPrinterPortLayout}
            label="忽略网络打印机端口"
            colon={false}
          >
            <Tooltip title="如勾选此参数,则下发扫描任务会忽略网络打印机默认端口9100,避免打印机直接打印该请求该端口的数据">
              <Icon type="exclamation-circle" style={{ marginLeft: 10, marginRight: 10 }} />
            </Tooltip>
            {getFieldDecorator('ignorePrinterPortCheck', {
              valuePropName: 'checked'
            })(<Checkbox onChange={changePorts} />)}
          </FormItem>
          <FormItem {...formItemLayout} key="portDetectionOnly" label="仅端口探活" colon={false}>
            <Tooltip title="系统会针对资产端口进行快速存活探测，如勾选此参数，则不会对存活端口进一步执行指纹探测、web指纹探测和操作系统深度探测操作。">
              <Icon type="exclamation-circle" style={{ marginLeft: -5, marginRight: 10 }} />
            </Tooltip>
            {getFieldDecorator('portDetectionOnly', {
              valuePropName: 'checked'
            })(
              <Checkbox
                disabled={getFieldValue('fingerprintDetection') || getFieldValue('depthDetect')}
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            key="fingerprintDetection"
            label="web指纹探测"
            colon={false}
          >
            <Tooltip title="系统会针对探测出来的具有http、https服务的端口进一步执行Web指纹探测。任务耗时会更长。">
              <Icon type="exclamation-circle" style={{ marginLeft: -5, marginRight: 10 }} />
            </Tooltip>
            {getFieldDecorator('fingerprintDetection', {
              valuePropName: 'checked'
            })(
              <Checkbox
                disabled={getFieldValue('portDetectionOnly')}
                onChange={changeFingerprintDetection}
              />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            key="depthDetect"
            label="操作系统深度探测"
            colon={false}
            style={{ marginLeft: '-2px' }}
          >
            <Tooltip title="系统会对目标进行深度探测，识别到更多的操作系统信息，但也会影响扫描速度，任务耗时会更长。">
              <Icon type="exclamation-circle" style={{ marginLeft: 10, marginRight: 10 }} />
            </Tooltip>
            {getFieldDecorator('depthDetect', {
              valuePropName: 'checked'
            })(<Checkbox disabled={getFieldValue('portDetectionOnly')} />)}
          </FormItem>
          <FormItem {...formItemLayout} key="protocolType" label="协议类型" colon={false}>
            {getFieldDecorator('protocolType', {
              rules: [
                {
                  validator: validatorCreator('协议类型', {
                    required: true
                  }),
                  required: true
                },
                { required: true, message: '协议至少勾选一个' }
              ]
            })(
              <CheckboxGroup className="protocol-group">
                <Checkbox value="ICMP">ICMP</Checkbox>
                <Checkbox value="UDP">UDP</Checkbox>
                <Checkbox value="TCP" disabled={getFieldValue('fingerprintDetection')}>
                  TCP
                </Checkbox>
              </CheckboxGroup>
            )}
          </FormItem>
        </Form>
      </Modal>
    </div>
  );
};

PortManageModal.propTypes = {
  form: PropTypes.object.isRequired,
  changeModalVisible: PropTypes.function,
  modalVisible: PropTypes.boolean,
  getPortList: PropTypes.function,
  detail: PropTypes.object,
  isAddPort: PropTypes.boolean
};

export default Form.create()(PortManageModal);
